package icedot.library.common.ui;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Scroller;

import icedot.library.common.base.Logger;

public class ExListView extends ListView implements UpdateHead.FootListener
{
    private UpdateHead _headView;
    private Scroller   _scrollerHead;
    private UpdateFoot _footView;
    private Scroller   _scrollerFoot;
    private float _lastY = -1;
    private boolean _enableHead;  //是否启用头部
    private boolean _enableFoot;  //是启用底部
    private boolean _showLastItem;   //列表的最后一项是否可见

    private OnScrollListener _scrollListener;  //
    private Context          _context;

    public ExListView(Context context)
    {
        super(context);
        initWithContext(context);
    }

    public ExListView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        initWithContext(context);
    }

    public ExListView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        initWithContext(context);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev)
    {
        if (_lastY == -1)
        {
            _lastY = ev.getRawY();
        }
        switch (ev.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                if (getFirstVisiblePosition() == 0 && _enableHead)
                {
                    _lastY = ev.getRawY();
                    _headView.setState(UpdateHead.Status.PRESSEDDOWN);
                }
                else if(isLastItemVisible() && _enableFoot && _footView.getState() != UpdateFoot.Status.FINISHALLDATA)
                {
                    _lastY = ev.getRawY();
                    _footView.setState(UpdateFoot.Status.PRESSEDDOWN);
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if (_enableHead && getFirstVisiblePosition() <= 1)
                {
                    _headView.setState(UpdateHead.Status.PRESSEDMOVE);
                    updateHeadHeight(ev.getRawY());
                }
                else if (_enableFoot && _footView.getState() != UpdateFoot.Status.FINISHALLDATA)
                {
                    _footView.setState(UpdateFoot.Status.PRESSEDMOVE);
                    updateFootView(ev.getRawY());
                }
                break;
            case MotionEvent.ACTION_UP:
                if (_enableHead && _footView.getState() != UpdateFoot.Status.UPDATEDATA && _headView.getVisiableHeight() > 0)
                {
                    _headView.setState(UpdateHead.Status.PRESSEDUP);
                    resetHead();
                }
                else
                {
                    resetHead();
                }
                if(_enableFoot && _headView.getState() != UpdateHead.Status.UPDATEDATA && _footView.getVisiableHeight() > 0
                    && _footView.getState() != UpdateFoot.Status.FINISHALLDATA)
                {
                    _footView.setState(UpdateFoot.Status.PRESSEDUP);
                    resetFoot();
                }
                else
                {
                    resetFoot();
                }
                break;
            default:
                _lastY = -1;
                break;
        }
        return super.onTouchEvent(ev);
    }

    private void initWithContext(Context context)
    {
        //super.setOnScrollListener(this);
        _context = context;
        _lastY = -1;
        _enableFoot = true;
        _enableHead = true;

        _headView = new UpdateHead(context);
        _headView.useHeadContent();

        _footView = new UpdateFoot(context);
        _footView.useFootContent();
        addHeaderView(_headView);
        addFooterView(_footView);
        _footView.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {

            }
        });
        _headView.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {

            }
        });

        _scrollerHead = new Scroller(context, new DecelerateInterpolator());
        _scrollerFoot = new Scroller(context,new DecelerateInterpolator());
    }

    public void enableHeadView(boolean enable)
    {
        _enableHead = enable;
    }

    public void enableFootView(boolean enable)
    {
        _enableFoot = enable;
    }

    /**
     * 修改列表头的高度
     *
     * @param y
     */
    private void updateHeadHeight(float y)
    {
        int   maxHeight = _headView.getMaxUpdateHead();
        float deltaY    = y - _lastY;
        if (getFirstVisiblePosition() == 0 && deltaY > 0)
        {
            if (deltaY >= maxHeight)
            {
                deltaY = maxHeight;
            }
            _headView.setVisiableHeight((int) deltaY);
        }
        else
        {
            _headView.setVisiableHeight(0);
        }
    }

    /**
     * 修改列表底部的高度
     *
     * @param y
     */
    private void updateFootView(float y)
    {
        int   maxHeight = _footView.getMaxLoadHeight();
        float deltaY    = _lastY - y;
        if (isLastItemVisible() && deltaY > 0)
        {
            if (deltaY >= maxHeight)
            {
                deltaY = maxHeight;
            }
            _footView.setVisiableHeight((int) deltaY);
        }
    }

    private void resetHead()
    {
        if(_headView.getVisiableHeight() == 0)
        {
            return;
        }
        UpdateHead.Status status = _headView.getState();
        int               height = 0;
        if (status == UpdateHead.Status.UPDATEDATA)
        {
            height = _headView.getMinUpdateHeight();
        }
        _scrollerHead.startScroll(0, _headView.getVisiableHeight(), 0, -(_headView.getVisiableHeight() - height), 800);
        invalidate();
    }

    /**
     * 删除底部
     */
    private void resetFoot()
    {
        if(_footView.getVisiableHeight() == 0)
        {
            return;
        }
        UpdateFoot.Status status = _footView.getState();
        int height = 0;
        if(status == UpdateFoot.Status.UPDATEDATA || status == UpdateFoot.Status.FINISHALLDATA)
        {
            height = _footView.getMinLoadHeight();
        }
        _scrollerFoot.startScroll(0, _footView.getVisiableHeight(), 0, -(_footView.getVisiableHeight() - height), 800);
        invalidate();
    }

    @Override
    public void computeScroll()
    {
        if (_scrollerHead.computeScrollOffset())
        {
//            Logger.showDebugMsg("ScrollHead", "Y:" + _scrollerHead.getCurrY());
            if (_headView.getVisiableHeight() > 0)
            {
                _headView.setVisiableHeight(_scrollerHead.getCurrY());
            }
            postInvalidate();
        }
        if(_scrollerFoot.computeScrollOffset())
        {
//            Logger.showDebugMsg("ScrollFoot", "Y:" + _scrollerFoot.getCurrY());
            if (_footView.getVisiableHeight() > 0)
            {
                _footView.setVisiableHeight(_scrollerFoot.getCurrY());
            }
            postInvalidate();
        }
        super.computeScroll();
    }

    /**
     * 头部完成
     */
    public void completeHead()
    {
        if(_headView.getState() == UpdateHead.Status.UPDATEDATA)
        {
            _headView.setState(UpdateHead.Status.RESET);
            if (_headView.getVisiableHeight() == 0)
            {
                return;
            }
            _scrollerHead.startScroll(0, _headView.getVisiableHeight(), 0, -_headView.getVisiableHeight(), 800);
            invalidate();
        }

    }

    public void completeFoot()
    {
        if(_footView.getState() == UpdateFoot.Status.UPDATEDATA)
        {
            _footView.setState(UpdateFoot.Status.RESET);
            if (_footView.getVisiableHeight() == 0)
            {
                return;
            }
            _scrollerFoot.startScroll(0, _footView.getVisiableHeight(), 0, -_footView.getVisiableHeight(), 800);
            invalidate();
        }
    }

    /**
     * 已经全部加载完成
     */
    public void setFootNoMore()
    {
        _footView.setState(UpdateFoot.Status.RESET);
        _footView.setState(UpdateFoot.Status.FINISHALLDATA);
        resetFoot();
    }

    public void clearFootFinish()
    {
        if(_footView.getState() == UpdateFoot.Status.FINISHALLDATA)
        {
            _footView.setState(UpdateFoot.Status.RESET);
            if (_footView.getVisiableHeight() == 0)
            {
                return;
            }
            _scrollerFoot.startScroll(0, _footView.getVisiableHeight(), 0, -_footView.getVisiableHeight(), 800);
            invalidate();
        }
    }

    public void setFootContent(String pressDown,String pressUp,String wait,String finish)
    {
        if(_footView != null)
        {
            _footView.setContent(UpdateFoot.Status.PRESSEDDOWN,pressDown);
            _footView.setContent(UpdateFoot.Status.PRESSEDUP,pressUp);
            _footView.setContent(UpdateFoot.Status.UPDATEDATA,wait);
            _footView.setContent(UpdateFoot.Status.FINISHALLDATA,finish);
        }
    }

    /**
     * 监听这个事件来获取拖动的结果
     *
     * @param ls
     */
    public void setUpdateViewListener(UpdateViewListener ls)
    {
        _headView.setNotifyListener(ls,this);
        _footView.setNotifyListener(ls);
    }


    @Override
    public void setOnScrollListener(OnScrollListener l)
    {
        _scrollListener = l;
    }

//    @Override
//    public void onScrollStateChanged(AbsListView view, int scrollState)
//    {
//        if (_scrollListener != null)
//        {
//            _scrollListener.onScrollStateChanged(view, scrollState);
//        }
//    }
//
//    @Override
//    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
//    {
//
//    }

    public boolean isLastItemVisible()
    {
        Adapter adapter = this.getAdapter();
        if (null == adapter || adapter.isEmpty())
        {
            return false;
        }
        final int lastItemPosition = adapter.getCount() - 1;//listview中position最大值，即最后一个

        final int lastVisiblePosition = this.getLastVisiblePosition();//listview中最后一个显示的position
        return (lastVisiblePosition + 1 >= lastItemPosition);
//        { //判断出是否是最后一个，lastVisiblePosition == lastItemPosition，但是包含footer时，lastVisiblePosition = lastItemPosition - 1
//            final int childIndex = lastVisiblePosition - this.getFirstVisiblePosition();//
//
//            final int childCount = this.getChildCount();//获取listview上显示的item属相
//
//            final int  index            = Math.min(childIndex, childCount - 1);
//            final View lastVisibleChild = this.getChildAt(index);
//            if (lastVisibleChild != null)
//            {
//                Logger.showDebugMsg("item:" + lastItemPosition + " listview item:" + lastVisiblePosition);
//                return lastVisibleChild.getBottom() <= this.getBottom();//最后一个是否显示完全
//            }
//            return true;
//        }
//        return false;
    }
}
